<template>
 <el-row class="login" type="flex" justify="center" align="middle">
  <el-col :xs="14" :sm="12" :md="10" :lg="8" :xl="6">
    <el-form
  label-position="top"
    :model="loginForm"
    :rules="rules"
    ref="loginForm"
    label-width="100px"
    class="login-form"
  >
    <el-form-item label="用户名" prop="username">
      <el-input v-model="loginForm.username"></el-input>
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input type="password" v-model="loginForm.password"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm('ruleForm')">登录</el-button>
      <el-button @click="resetForm('loginForm')">重置</el-button>
    </el-form-item>
  </el-form>
  </el-col>
</el-row>

</template>

<script>
// 导入axios
import axios from 'axios'

export default {
  data () {
    return {
      loginForm: {
        username: 'admin',
        password: '123456'
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 6, message: '用户名长度为3到6个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 12, message: '密码长度为6-12个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    submitForm () {
      this.$refs.loginForm.validate(async valid => {
        if (!valid) {
          return false
        }

        // 验证成功：登录的代码逻辑
        const res = await axios.post('http://localhost:8888/api/private/v1/login', this.loginForm)
        console.log(res)
        if (res.data.meta.status === 200) {
          // 登陆成功
          // 3 将登陆标识 token 存储到 localStorage 中
          // 注意：先保存 token ，再跳转路由，因为 跳转路由的时候，导航守卫中获取了 token。如果在获取token前，没有存储 token ，就出问题了
          localStorage.setItem('token', res.data.data.token)
          // 1-跳转到首页
          this.$router.push('/home')
          // 2-登陆成功的消息提示'
          this.$message({
            message: res.data.meta.msg,
            type: 'success',
            duration: 800
          })
        } else {
          // 登陆失败
          this.$message({
            type: 'error',
            message: res.data.meta.msg,
            duration: 1000
          })
        }
      })
    },
    // 表单重置
    resetForm (formName) {
      // 对整个表单进行重置，将所有字段值重置为初始值并移除校验结果
      this.$refs[formName].resetFields()
    }
  }
}
</script>

<style>
.login {
  height: 100%;
  background-color: #2d434c;
}
.login-form {
  padding: 25px;
  border-radius: 15px;
  background-color: #fff;
}
</style>
